<!-- EditableCell.vue -->
<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue';
import { Edit } from '@element-plus/icons-vue'; // 引入编辑图标

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  placeholder: {
    type: String,
    default: '双击编辑'
  },
  defaultValue: {
    type: [String, Number],
    default: ''
  },
  type: {
    type: String,
    default: 'text'
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

const isEditing = ref(false);
const editValue = ref('');
const inputRef = ref(null);

const startEdit = () => {
  isEditing.value = true;
  editValue.value = props.modelValue || '';
  nextTick(() => {
    inputRef.value?.input?.focus();
  });
};

const save = () => {
  const newValue = editValue.value.trim();
  emit('update:modelValue', newValue);
  emit('change', newValue);
  isEditing.value = false;
};

const cancel = () => {
  isEditing.value = false;
};

const handleClickOutside = (e) => {
  if (inputRef.value?.input?.contains(e.target)) return;
  const cell = e.target.closest('.editable-cell');
  if (cell) return;
  if (isEditing.value) cancel();
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<template>
  <div class="editable-cell" @dblclick="startEdit" @click.stop>
    <!-- 显示模式 -->
    <template v-if="!isEditing">
      <span class="cell-text"> {{ modelValue || placeholder }} 123 </span>
      <el-icon class="edit-hint">
        <Edit />
      </el-icon>
    </template>

    <!-- 编辑模式 -->
    <template v-else>
      <el-input
        ref="inputRef"
        v-model="editValue"
        size="small"
        style="width: 100%"
        :type="type"
        col="5"
        @keyup.enter="save"
        @keyup.escape="cancel"
        @click.stop
      />
    </template>
  </div>
</template>

<style scoped>
.editable-cell {
  padding: 2px 6px;
  min-height: 24px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  border-radius: 3px;
  transition: background-color 0.2s;
  width: 100%;
}

.editable-cell:hover {
  background-color: #f7f7f7;
}

.cell-text {
  color: #333;
  font-size: 14px;
}

.edit-hint {
  font-size: 14px;
  color: #999;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.editable-cell:hover .edit-hint {
  opacity: 1;
  color: #409eff; /* Element Plus 主色 */
}
</style>
